<template>
  <el-container>
    <el-main class="huiLanCrudRoleUser">
      <div class="tempForm">
        <avue-form
          ref="tempFormRef"
          :option="deptTreeOption"
          v-if="userInfo.isAdmin != 0"
        >
        </avue-form>
        <avue-form ref="tempFormRef" :option="deptOption" v-else> </avue-form>
      </div>
      <HuilanBasicSearchbar
        :model="searchForm"
        :fields="searchFieldList"
        @search="searchChange"
        @refresh="refreshChange"
        @reset="searchReset"
        ref="searchFormRef"
      >
        <template v-slot:deptId>
          <div class="huiLanSearchCascader">
            <el-input v-model="deptId" />
          </div>
        </template>
      </HuilanBasicSearchbar>
      <avue-crud
        :option="option"
        :search.sync="query"
        :table-loading="loading"
        :data="data"
        ref="crud"
        :page.sync="page"
        @search-change="searchChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            icon="el-icon-plus"
            size="small"
            :disabled="handleCanAdd(scope.row)"
            @click.stop="handleAdd(scope.row, scope.index)"
            >{{ $t("aicosCommon.addBtn") }}
          </el-button>
        </template>
      </avue-crud>
    </el-main>
    <el-aside width="200px">
      <el-card
        shadow="never"
        :header="$t('system.role.selectedUsers')"
        :body-style="{ padding: '5px', height: '460px', overflow: 'auto' }"
      >
        <List :data="value" :props="lisProps" @itemRemove="handleRemove" />
      </el-card>
    </el-aside>
  </el-container>
</template>
<script>
// import { getCanManagerDeptByAccount } from "@/api/system/dept";
import { isNull } from "@/util/qsgCommon.js";
import { getDeptTree } from "@/api/optOrg/optOrg";
import { mapGetters } from "vuex";
import { getUserListPageByAuth3 } from "@/api/system/role";
import List from "@/components/list";
import i18n from "@/lang";

export default {
  components: {
    List,
  },
  props: {
    value: {
      type: Array,
      default() {
        return [];
      },
    },
    role: {
      type: Object,
      default() {
        return {};
      },
    },
    managerDeptArr: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      managerDept: [],
      firstId: "0",
      deptTreeOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "",
            prop: "tempDeptId",
            placeholder:
              i18n.t("aicosCommon.pleaseSelect") +
              i18n.t("system.dept.department"),
            labelWidth: 0,
            type: "tree",
            lazy: true,
            popperClass: "huiLanSelectTree",
            filterText: i18n.t("kwRobotStudy.filterText"),
            popperAppendToBody: false,
            defaultExpandedKeys: ["0"],

            props: {
              label: "deptName",
              children: "children",
              value: "id",
            },
            created: true,
            treeLoad: (node, resolve) => {
              if (node.level === 0) {
                resolve([
                  {
                    deptName: i18n.t("system.user.departmentDirectory"),
                    id: "0",
                  },
                ]);
                return;
              }

              const dataParam = {
                parentId: node.data.id,
                mode: "all",
              };
              getDeptTree(dataParam).then((res) => {
                const dataRes = res.data.data.retList;
                resolve(
                  dataRes.map((item) => {
                    return {
                      ...item,
                      leaf: item.isLeaf === "1",
                    };
                  })
                );
              });
            },
            change: ({ value /*,column*/ }) => {
              //console.log(value);
              this.query.deptId = value;
            },
          },
        ],
      },
      searchForm: {},
      deptOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "",
            prop: "tempDeptId",
            placeholder:
              i18n.t("aicosCommon.pleaseSelect") +
              i18n.t("system.dept.department"),
            labelWidth: 0,
            type: "tree",
            lazy: false,
            popperClass: "huiLanSelectTree",
            filterText: i18n.t("kwRobotStudy.filterText"),
            popperAppendToBody: false,
            defaultExpandedKeys: ["0"],
            props: {
              label: "deptName",
              children: "children",
              value: "id",
            },
            dicData: [],
            created: true,
            change: ({ value /*,column*/ }) => {
              //console.log(value);
              this.query.deptId = value;
            },
          },
        ],
      },
      query: {
        deptId: 0,
      },
      loading: true,
      platformLoading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        height: 400,
        calcHeight: 80,
        tip: false,
        searchShow: true,
        searchSpan: 8,
        gutter: 2,
        searchMenuSpan: 8,
        border: false,
        index: false,
        selection: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 70,
        //dialogType: 'drawer',
        dialogClickModal: false,
        dialogWidth: "40%",
        column: [
          {
            label: this.$t("system.user.userName"),
            prop: "account",
            search: true,
            display: false,
          },
          {
            label: this.$t("system.user.realName"),
            prop: "realName",
            search: true,
            display: false,
          },
          {
            label: this.$t("system.dept.deptId"),
            prop: "deptId",
            //search: true,
            hide: true,
            display: true,
            solt: "deptId",
          },
          {
            label: this.$t("system.user.enableStatus"),
            prop: "status",
            type: "radio",
            width: 130,
            dicData: [
              {
                label: this.$t("system.user.enable"),
                value: "1",
              },
              {
                label: this.$t("system.user.deactivate"),
                value: "0",
              },
            ],
          },
          {
            label: this.$t("system.user.lockingState"),
            prop: "isLock",
            type: "radio",
            width: 130,
            dicData: [
              {
                label: this.$t("system.user.lock"),
                value: "1",
              },
              {
                label: this.$t("system.user.unLocked"),
                value: "0",
              },
            ],
          },
        ],
      },
      data: [],
      // selectedUsers: [],
      lisProps: {
        key: "id",
        label: "realName",
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo", "managerDeptId"]),
  },
  mounted() {
    /*处理新规范表格的搜索*/
    const listColumn = this.option.column;
    const formColumn = listColumn.filter((item) => item.search === true);
    formColumn.map((item) => {
      item.placeholder =
        (item.type == "select"
          ? this.$t("aicosCommon.pleaseSelect")
          : this.$t("aicosCommon.pleaseInput")) + item.label;
    });
    this.searchFieldList = formColumn;
    /*处理下拉树再次下来无数据的问题*/
    this.$refs.tempFormRef.$refs.tempDeptId[0].$refs.temp.created = true;
    this.moveDeptSel();
    // isAdmin:0表示普通人员，3管理员，4安全管理员
    if (this.userInfo.isAdmin == 0) {
      // this.managerDept = this.deepClone(this.managerDeptId);
      // getCanManagerDeptByAccount().then((res) => {
      //   let data = res.data.data;
      //   this.deptOption.column[0].dicData = [
      //     {
      //       name: this.$t("system.dept.dept"),
      //       id: "0",
      //       children: this.managerDeptArr,
      //     },
      //   ];
      //   this.traverseTree(this.deptOption.column[0].dicData);
      //   this.query.deptId = this.managerDept[0];
      //   this.onLoad(this.page);
      // });
      this.deptOption.column[0].dicData = [
        {
          deptName: this.$t("system.dept.dept"),
          id: "0",
          disabled: true,
          children: this.managerDeptArr,
        },
      ];
    }
  },
  methods: {
    traverseTree(node) {
      if (node) {
        node.forEach((item) => {
          let flag = true;
          if (this.managerDept.includes(item.id)) {
            flag = false;
          }
          if (flag) {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
          this.traverseTree(item.children);
        });
      }
    },
    moveDeptSel() {
      //console.log(this.$refs);
      const tempRef = this.$refs.tempFormRef.getPropRef("tempDeptId").$el;
      const toRef = this.$refs.searchFormRef.$refs.form.$el;
      //const toRef = this.$refs.searchFormRef.$refs.form.getPropRef('deptId').$el;
      toRef.prepend(tempRef);
    },
    searchReset() {
      this.$refs.tempFormRef.resetForm();
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params) {
      this.query = {
        ...this.query,
        ...params,
        ...this.searchForm,
      };
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      const postData = {
        roleId: this.role.id,
        current: page.currentPage,
        size: page.pageSize,
        ...params,
        ...this.query,
        deptId: this.query.deptId || this.firstId,
      };
      this.loading = true;
      if (this.userInfo.isAdmin == 0 && isNull(this.managerDeptArr)) {
        this.loading = false;
        this.data = [];
      } else {
        getUserListPageByAuth3(postData).then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
        });
      }
    },
    handleCanAdd(row) {
      return this.value.some((item) => item.id === row.id);
    },
    handleAdd(row /*, index*/) {
      this.value.push(row);
      this.$emit("input", this.value);
    },
    handleRemove(item, index) {
      this.value.splice(index, 1);
      this.$emit("input", this.value);
    },
  },
};
</script>
<style lang="scss" scoped>
.huiLanCrudRoleUser {
  /deep/.avue-crud {
    .avue-crud__search,
    .avue-crud__menu {
      width: 0;
      height: 0;
      overflow: hidden;
      display: none;
    }
  }

  .tempForm {
    width: 0;
    height: 0;
    overflow: hidden;
    display: none;
  }

  /deep/.Huilan-basic-search-form {
    padding-right: 10px;
    & > .el-form-item:not(.search-from-tool) {
      width: 170px;
    }

    & > :first-child {
      margin-right: 10px;
      width: 170px;
    }
  }
}
</style>
